import logging
from common import setup_logging

class CommandExecutor:
    """命令行执行器，用于非交互式执行命令"""
    
    def __init__(self, sftp_instance, continue_on_error=False):
        self.sftp = sftp_instance
        self.sftp.non_interactive = True
        self.continue_on_error = continue_on_error
        self.logger = logging.getLogger(__name__)
        self.execution_stats = {
            'total': 0,
            'successful': 0,
            'failed': 0
        }
    
    def execute(self, command):
        """执行单条或多条命令（分号分隔）"""
        # 检查命令是否包含分号
        if ';' in command:
            # 按分号分割命令
            commands = [cmd.strip() for cmd in command.split(';') if cmd.strip()]            
            if not commands:
                return True
            return self.execute_multiple_commands(command)
        else:
            return self._execute_single_command(command)
    
    def _execute_single_command(self, command):
        """执行单条命令"""
        try:
            self.execution_stats['total'] += 1
            self.logger.info(f"执行命令: {command}")
            
            # 解析命令
            parts = command.split()
            if not parts:
                return True
                
            cmd_name = parts[0]
            args = ' '.join(parts[1:])
            
            # 检查命令是否存在
            if not hasattr(self.sftp, 'do_' + cmd_name):
                self.logger.error(f"未知命令: {cmd_name}")
                print(f"❌❌❌❌ 未知命令: {cmd_name}")
                self.execution_stats['failed'] += 1
                return False
            
            # 执行命令
            method = getattr(self.sftp, 'do_' + cmd_name)
            result = method(args)
            
            # 检查命令执行结果
            if result is False:
                self.logger.error(f"命令执行失败: {command}")
                print(f"❌❌❌❌ 命令执行失败: {command}")
                self.execution_stats['failed'] += 1
                return False
                
            self.logger.info(f"命令执行成功: {command}")
            self.execution_stats['successful'] += 1
            return True
            
        except Exception as e:
            self.logger.error(f"执行命令时出错: {e}")
            print(f"❌❌❌❌ 执行命令时出错: {e}")
            self.execution_stats['failed'] += 1
            return False
    
    def execute_multiple_commands(self, commands):
        """执行多条命令"""
        # # 按分号分割命令
        # commands = [cmd.strip() for cmd in command.split(';') if cmd.strip()]
        if not commands:
            return True

        success = True
        executed_count = 0
        failed_count = 0
        
        self.logger.info(f"开始执行 {len(commands)} 条分号分隔的命令")
        print(f"📋 开始执行 {len(commands)} 条分号分隔的命令")
        
        for i, cmd in enumerate(commands, 1):
            print(f"\n[{i}/{len(commands)}] 执行命令: {cmd}")
            
            # 执行单条命令
            if self._execute_single_command(cmd):
                executed_count += 1
            else:
                success = False
                failed_count += 1
                
                # 如果设置了遇到错误停止，则中断执行
                if not self.continue_on_error:
                    self.logger.warning("遇到错误，停止执行后续命令")
                    print("⚠️  遇到错误，停止执行后续命令")
                    break
        
        # 输出执行结果摘要
        print(f"\n📊 执行完成: {executed_count} 成功, {failed_count} 失败")
        
        if success:
            self.logger.info(f"所有命令执行成功: {executed_count} 条命令")
            print("✅ 所有命令执行成功")
        else:
            self.logger.warning(f"部分命令执行失败: {executed_count} 成功, {failed_count} 失败")
            print("❌ 部分命令执行失败")
        
        return success

    def get_stats(self):
        """获取执行统计信息"""
        success_rate = self.execution_stats['successful'] / self.execution_stats['total'] * 100 if self.execution_stats['total'] > 0 else 0
        return {
            'total': self.execution_stats['total'],
            'successful': self.execution_stats['successful'],
            'failed': self.execution_stats['failed'],
            'success_rate': success_rate
        }
    
    def show_stats(self):
        """显示执行统计信息"""
        stats = self.get_stats()
        
        print("\n📊 执行统计:")
        print("=" * 40)
        print(f"  总命令数: {stats['total']}")
        print(f"  成功: {stats['successful']}")
        print(f"  失败: {stats['failed']}")
        print(f"  成功率: {stats['success_rate']:.1f}%")

class CommandFileReader:
    """命令文件读取器，用于从文件读取并执行命令"""
    
    def __init__(self, executor):
        self.executor = executor
    
    def read_and_execute(self, file_path):
        """从文件读取命令并执行"""
        try:
            path = file_path.strip() if file_path else ''
            with open(path, 'r', encoding='utf-8') as f:
                commands = []
                for line in f:
                    line = line.strip()
                    # 跳过空行和注释
                    if not line or line.startswith('#'):
                        continue
                    commands.append(line)
                return self.executor.execute_multiple_commands(commands)
        except FileNotFoundError:
            print(f"❌❌❌❌ 命令文件不存在: {file_path}")
            return False
        except Exception as e:
            print(f"❌❌❌❌ 读取命令文件时出错: {e}")
            return False
